<?php
// +----------------------------------------------------------------------
// | 海豚PHP框架 [ DolphinPHP ]
// +----------------------------------------------------------------------
// | 版权所有 2016~2017 河源市卓锐科技有限公司 [ http://www.zrthink.com ]
// +----------------------------------------------------------------------
// | 官方网站: http://dolphinphp.com
// +----------------------------------------------------------------------
// | 开源协议 ( http://www.apache.org/licenses/LICENSE-2.0 )
// +----------------------------------------------------------------------

namespace app\shop\admin;

use app\admin\controller\Admin;
use app\common\builder\ZBuilder;
use app\shop\model\Shop as ShopModel;
use app\shop\model\ShopStatus as ShopStatusModel;

use think\Db;

/**             
 * 行为管理控制器
 * @package app\admin\controller
 */
class Shop extends Admin
{
    public function index()
    {
        unset($_SESSION['id']);
        cookie('__forward__', $_SERVER['REQUEST_URI']);
        $shoptypes=Db::name('shop_type')->column('id,shoptype');
        $status=ShopStatusModel::getstatus();
        $is_enable=ShopStatusModel::getIsEnable();
        $map = $this->getMap();
        $from_time=input('date1');
        $to_time=input('date2');
        $search=input('search');
        $status_shop=input('shop_status');

        // 数据列表
        if(!empty($status_shop) || $status_shop=='0' || !empty($search) || !empty($from_time) || !empty($to_time)){
            if($from_time && $to_time){
                $from_time=strtotime($from_time.' 00:00:00');
                $to_time=strtotime($to_time.' 23:59:59');
                $map['createtime']=['between', [$from_time, $to_time]];
            }
            if($status_shop!='0'){
                $map['status']=$status_shop;
            }
            if($status_shop=='0'){
                $map['status']='0';
            }
            if($search){
                $map["name|email|shopmsg|contacts"]=['like',"%$search%"];
            }
        }
            $data_list = Db::name('shop')->where($map)->order('id desc')->paginate();

        // 分页数据
        $page = $data_list->render();
        // 使用ZBuilder快速创建数据表格
        return ZBuilder::make('mix')
            ->setPageTitle('筛选')
            ->addSelect('shop_status', '审核状态', '', $status,$status_shop)
            ->addText('search','搜索条件','',$search)
            ->addDaterange('date1,date2', '日期范围')
            ->addBtn('<button type="submit" class="btn  btn-primary btn-rounded">确定搜索</button>')
            ->hideBtn('submit,back')
            ->layout(['search'=>2,'date1'=>4,'date2'=>4,'form_group_btnGroup'=>2,'shop_status'=>2,'shop_type'=>2])
            ->setPageTitle('店铺列表') // 设置页面标题
            ->setTablename('shop') // 设置数据表名
            ->setPrimaryKey('id')
            ->addColumns([ // 批量添加列
                ['shop_logo', '店铺logo', 'picture'],
                ['name', '店铺名称','text.edit','','','fix-table-td'],
                ['shoptype', '店铺类型','select',$shoptypes,'fix-table-td'],
                ['shopmsg', '店铺描述','textarea.edit','','','fix-table-td'],
                ['contacts', '联系人','text.edit','','','fix-table-td'],
                ['mobile', '手机号','text.edit','','','fix-table-td'],
                ['tel', '固定电话','','','','fix-table-td'],
                ['email', '邮箱','','','','fix-table-td'],
                ['status', '审核状态','status','',$status],
                ['is_enable', '是否启用','status','',$is_enable],
                ['right_button', '操作', 'btn']
            ])
            ->addValidate('Shopedit', 'name,shoptype,contacts,mobile') // 添加快捷编辑的验证器
            ->addFilter('shoptype',$shoptypes)
            ->addFilter('is_enable',$is_enable)
            ->addFilter('status',$status)
            ->addTopButtons('add') // 批量添加顶部按钮
            -> addTopButton('enable',['title'=>'审核'])
            -> addTopButton('enable',['title'=>'启用','icon' => 'fa fa-fw fa-unlock','href' => url('isenable')])
            -> addTopButton('disable',['title'=>'禁用','icon'=>'fa fa-fw fa-unlock-alt'])
            ->addrightButton('edit')// 批量添加右侧按钮
            ->addrightButton('edit',['title'=>'查看','icon'=>'fa fa-fw fa-file-text-o','href'=>url('look',['id' => '__id__'])])
            ->setRowList($data_list) // 设置表格数据
            ->isAjax(false)
            ->setFormMethod('get')
            ->setPages($page) // 设置分页数据
            ->fetch(); // 渲染页面
    }
    //营业执照信息新增
    public function adds(){
        $id=session('id');
        if ($this->request->isPost()) {
            $data = $this->request->post();
//            // 验证
            $result = $this->validate($data,'Business');
            // 验证失败 输出错误信息
            if(true !== $result) {
                return $this->error($result);
            }else{
                $data['shopid']=$id;
                $data['typeid']=1;
                $data['createtime']=time();
                $data['updatetime']=time();
            }
            $res=Db::name('business_license')->insertGetid($data);
            if ($res) {
                $details = "所属模块('shop'),操作日志('营业执照信息新增'),营业执照编号('$res')";
                action_log('business_license_add', 'shop', $res, UID, $details);
                return $this->success('新增成功',url('shop/Shop/addbank'));
            } else {
                return $this->error('新增失败');
                unset($_SESSION['id']);
            }
        }
        // 使用ZBuilder快速创建表单
        return ZBuilder::make('form')
            ->setPageTitle('添加营业执照信息') // 设置页面标题
            ->addFormItems([ // 批量添加表单项
                ['text', 'name', '法人代表姓名'],
                ['image', 'cardimg','法人代表身份证复印件'],
                ['image', 'shoppersoncodeimg','负责人身份证复印件'],
                ['static','',''],
                ['text', 'businesslicenseno', '营业执照号', ''],
                ['date', 'effectivetime', '营业执照有效期',''],
                ['image', 'effectiveimg', '营业执照副本图片'],
                ['static','',''],
                ['text', 'registeredcapital', '注册资本', ''],
                ['text', 'organizationcode', '组织机构代码'],
                ['image', 'organizationcodeimg','组织机构代码证复印件'],
                ['static','',''],
                ['text', 'generaltaxpayerproof', '一般纳税人说明'],
                ['text', 'taxcode', '纳税类型码'],
                ['text', 'taxno', '税务登记号码'],
                ['image', 'taximg', '税务登记证复印件'],
                ['textarea', 'scope', '经营范围', '']
            ])
            ->layout(['businesslicenseno'=>3,'effectivetime'=>3,'registeredcapital'=>3,'organizationcode'=>3,'generaltaxpayerproof'=>3,
            'name'=>3,'taxcode'=>3,'taxno'=>3,'effectiveimg'=>3,'taximg'=>3,'organizationcodeimg'=>3,'shoppersoncodeimg'=>3,'cardimg'=>3
            ])
            ->fetch();
    }
    //店铺新增
    public function add()
    {
        $list_province =Db::name("admin_area")->where("pid=0")->column("id,name");
        $shoptype=Db::name("goods_type")->where('parentid','neq',0)->column("typeid,classname");
        $shoplevel=Db::name("shop_level")->where("status=1")->column("id,shopname");
        $shop_type=Db::name("shop_type")->where("status=1")->column("id,shoptype");
        // 保存数据
        if ($this->request->isPost()) {
            $data = $this->request->post();
            // 验证
            $result = $this->validate($data,'AddShop');
            // 验证失败 输出错误信息
            if(true !== $result) {
                return $this->error($result);
            }else{
                $member=$data['shopid'][0];
                $data['memberid']=$member;
                $data['password']=crypt($data['password'],'CRYPT_MD5');
                $res_province=Db::name("admin_area")->where("id=".$data['provinceid'])->find();
                $res_city=Db::name("admin_area")->where("id=".$data['cityid'])->find();
                $data['province']=$province=$res_province['name'];
                $data['city']=$city=$res_city['name'];
                if(!empty($data['shopcategory'])){
                    $goods=implode(',',$data['shopcategory']);
                    $data['shopcategory']=$goods;
                }
                if(!empty($data['townid'])){
                    $res_town=Db::name("admin_area")->where("id=".$data['townid'])->find();
                    $data['town']=$town=$res_town['name'];
                }
                if(empty($data['addr'])){
                    if(empty($data['townid'])){
                        $data['addr']=$province.$city;
                    }else{
                        $data['addr']=$province.$city.$town;
                    }
                }else{
                    if(strpos($data['addr'],'省') || strpos($data['addr'],'市')){
                        $data['addr']=$data['addr'];
                    }else{
                        if(empty($data['townid'])){
                            $data['addr']=$province.$city.$data['addr'];
                        }else{
                            $data['addr']=$province.$city.$town.$data['addr'];
                        }
                    }

                }
                $data['createtime']=time();
                $data['updatetime']=time();
            }

            $res=Db::name('shop')->insertGetid($data);
            if ($res) {
                session('id',$res);
                if(!empty($data['shopcategory'])){
                    $type['shopid']=$res;
                    $type['typeid']=$data['shopcategory'];
                    $typename=explode(',',$type['typeid']);
                    $type_name='';
                    foreach ($typename as $value){
                        $name=Db::name('goods_type')->where('typeid',$value)->field('classname')->find();
                        $type_name.=$name['classname'].',';
                    }
                    $type['typename']=trim($type_name,',');
                    Db::name('type_auditing')->insert($type);
                }
                $details = "所属模块('shop'),操作日志('店铺新增'),店铺编号('$res')";
                action_log('shop_add', 'shop', $res, UID, $details);
                return $this->success('新增成功', url('shop/Shop/adds'));
            } else {
                return $this->error('新增失败');
            }

        }


        // 使用ZBuilder快速创建表单
        return ZBuilder::make('form')
            ->setPageTitle('新增') // 设置页面标题
            ->addFormItems([['image', 'shop_logo', '店铺logo']])
            ->addSelect('shopid','选择会员','','','','ajax','',['url'=>'/admin.php/Shop/Shop/memberlist','datakey'=>'id','dataname'=>'name'])
            ->addFormItems([ // 批量添加表单项
                ['text', 'name', '店铺名称', '必填'],
                ['select', 'shoplevelid', '店铺等级','',$shoplevel],
                ['select', 'shoptype', '店铺类型', '',$shop_type],
                ['textarea', 'shopmsg', '店铺描述', ''],
                ['select', 'shopcategory', '店铺经营类目', '',$shoptype,'','multiple'],
                ['text', 'contacts', '联系人'],
                ['text', 'mobile', '手机号'],
                ['text', 'tel', '固话'],
                ['text', 'email', '邮箱'],
                ['text', 'qq', 'qq'],
                ['password', 'password', '密码'],
                ['static', '', ''],
                ['linkage', 'provinceid', '选择省份','',$list_province,'',url('get_city'),'cityid,townid'],
                ['linkage', 'cityid', '选择城市','','','',url('get_area'),'townid'],
                ['select', 'townid', '选择区域'],
                ['text', 'addr', '详细地址']
            ])
            ->layout(['shopid'=>3,'name'=>3,'shoplevelid'=>3,'shoptype'=>3,'shopcategory'=>12,'contacts'=>3,'mobile'=>3,
                'tel'=>3,'email'=>3,'qq'=>3,'password'=>3,'provinceid'=>2,'cityid'=>2,'townid'=>2,'addr'=>5
            ])
            ->fetch();
    }
    //新增银行信息
    public function addbank(){
        $shopid=session('id');
        if ($this->request->isPost()) {
            $data = $this->request->post();
            // 验证
            $result = $this->validate($data,'ShopSettlement');
            // 验证失败 输出错误信息
            if(true !== $result) {
                return $this->error($result);
            }else{
                $data['shopid']=$shopid;
                $data['createtime']=time();
                $data['updatetime']=time();
            }
            $res=Db::name('shop_settlement')->insert($data);
            if ($res) {
                return $this->success('新增成功',url('shop/Shop/addblance'));
            } else {
                return $this->error('新增失败');
            }
        }
        // 使用ZBuilder快速创建表单
        return ZBuilder::make('form')
            ->setPageTitle('新增银行信息') // 设置页面标题
            ->addFormItems([ // 批量添加表单项
                ['text', 'account_name', '银行开户名', ''],
                ['text', 'bank_no', '公司银行账户',''],
                ['text', 'bank_name', '开户银行支行名称', ''],
                ['text', 'subbranch_id', '支行联行号', ''],
                ['text', 'band_addr', '开户银行所在地', ''],
            ])
            ->layout(['account_name'=>4,'bank_no'=>4,'bank_name'=>4,'subbranch_id'=>4,'band_addr'=>4 ])
            ->fetch();
    }
    //新增开票信息
    public function addblance(){
        $shopid=session('id');
        $list_province =Db::name("admin_area")->where("pid=0")->column("id,name");
        $invoiceType=Db::name('invoice_type')->where('status=1')->column('invoice_id,invoice_type');
        if ($this->request->isPost()) {
            $data = $this->request->post();
//            // 验证
            $result = $this->validate($data,'Bank');
            // 验证失败 输出错误信息
            if(true !== $result) {
                return $this->error($result);
            }else{
                $data['shopid']=$shopid;
                $data['typeid']=1;
                $c_province=Db::name("admin_area")->where("id=".$data['c_provinceid'])->find();
                $c_city=Db::name("admin_area")->where("id=".$data['c_cityid'])->find();
                if(!empty($data['c_townid'])){
                    $c_town=Db::name("admin_area")->where("id=".$data['c_townid'])->find();
                }
                if(empty($data['bandaddr'])){
                    if(empty($c_town['name'])){
                        $data['bandaddr']=$c_province['name'].$c_city['name'];
                    }else{
                        $data['bandaddr']=$c_province['name'].$c_city['name'].$c_town['name'];
                    }
                }else{
                    if(strpos($data['bandaddr'],'省') || strpos($data['bandaddr'],'市')){
                        $data['bandaddr']=$data['bandaddr'];
                    }else{
                        if(empty($c_town['name'])){
                            $data['bandaddr']=$c_province['name'].$c_city['name'].$data['bandaddr'];
                        }else{
                            $data['bandaddr']=$c_province['name'].$c_city['name'].$c_town['name'].$data['bandaddr'];
                        }
                    }
                }
                $res_province=Db::name("admin_area")->where("id=".$data['provinceid'])->find();
                $res_city=Db::name("admin_area")->where("id=".$data['cityid'])->find();
                if(!empty($data['townid'])){
                    $res_town=Db::name("admin_area")->where("id=".$data['townid'])->find();
                }
                if(empty($data['addr'])){
                    if(empty($res_town['name'])){
                        $data['signup_address']=$res_province['name'].$res_city['name'];
                    }else{
                        $data['signup_address']=$res_province['name'].$res_city['name'].$res_town['name'];
                    }
                }else{
                    if(strpos($data['addr'],'省') || strpos($data['addr'],'市')){
                        $data['signup_address']=$data['addr'];
                    }else{
                        if(empty($res_town['name'])){
                            $data['signup_address']=$res_province['name'].$res_city['name'].$data['addr'];
                        }else{
                            $data['signup_address']=$res_province['name'].$res_city['name'].$res_town['name'].$data['addr'];
                        }
                    }
                }
                $data['createtime']=time();
                $data['updatetime']=time();
            }
            $res=Db::name('member_balance')->insert($data);
            if ($res) {
                return $this->success('新增成功',cookie('__forward__'));
                unset($_SESSION['id']);
            } else {
                return $this->error('新增失败');
                unset($_SESSION['id']);
            }
        }
        // 使用ZBuilder快速创建表单
        return ZBuilder::make('form')
            ->setPageTitle('新增开票信息') // 设置页面标题
            ->addFormItems([ // 批量添加表单项
                ['select', 'invoice_type', '发票类型','',$invoiceType],
                ['text', 'company', '单位名称', ''],
                ['text', 'taxpayer_no', '纳税人识别号', ''],
                ['text', 'tel', '电话', ''],
                ['text', 'accountname', '银行开户名', ''],
                ['text', 'bankno', '公司银行账户',''],
                ['text', 'bankname', '开户银行支行名称', ''],
                ['text', 'bankid', '支行联行号', ''],
                ['linkage', 'c_provinceid', '选择省份','',$list_province,'',url('c_city'),'c_cityid,c_townid'],
                ['linkage', 'c_cityid', '选择城市','','','',url('c_area'),'c_townid'],
                ['select', 'c_townid', '选择区域',''],
                ['text', 'bandaddr', '开户银行所在地', ''],
                ['linkage', 'provinceid', '选择省份','',$list_province,'',url('get_city'),'cityid,townid'],
                ['linkage', 'cityid', '选择城市','','','',url('get_area'),'townid'],
                ['select', 'townid', '选择区域',''],
                ['text', 'addr', '注册地址', ''],
            ])
            ->layout(['accountname'=>3,'bankno'=>3,'bankname'=>3,'bankid'=>3,'bandaddr'=>3,'invoice_type'=>3,
                'company'=>3,'taxpayer_no'=>3,'tel'=>3,'provinceid'=>3,'cityid'=>3,'townid'=>3,'addr'=>3,'c_provinceid'=>3,'c_cityid'=>3,'c_townid'=>3])
            ->fetch();
    }

    //店铺编辑
    public function edit($id ='',$group = 'tab1')
    {
        session('id',$id);
        $list_tab = [
            'tab1' => ['title' => '基础信息', 'url' => url('edit', ['group' => 'tab1'])],
            'tab2' => ['title' => '证照信息', 'url' => url('edit', ['group' => 'tab2'])],
//            'tab3' => ['title' => '店铺银行信息', 'url' => url('edit', ['group' => 'tab3'])],
            'tab4' => ['title' => '开票信息', 'url' => url('edit', ['group' => 'tab4'])],
        ];
        $url=cookie('__forward__');
        $js = <<<EOF
            <script type="text/javascript">
              function back(){
              window.location.href="$url";
              }
            </script>
EOF;
        switch ($group) {
            case 'tab1':
                $id=session('id');
                if ($id === null) return $this->error('缺少参数');
                $status=ShopStatusModel::getstatus();
                $is_enable=ShopStatusModel::getIsEnable();
                $shoptype=Db::name("goods_type")->where('parentid','neq',0)->column("typeid,classname");
                $shopinfo = Db::name('shop')->where('id',$id)->field('password',true)->find();
                $shoplevel=Db::name("shop_level")->where("status=1")->column("id,shopname");
                $shop_type=Db::name("shop_type")->where("status=1")->column("id,shoptype");
                $member_id=$shopinfo['memberid'];
                $memberinfo=Db::name("member")->where("id",$member_id)->find();
                $arr = [];
                $arr[$memberinfo['id']] = $memberinfo['name'];
                $testid = $memberinfo['id'];

                $list_province = Db::name("admin_area")->where("pid=0")->column("id,name");
                if(!empty($shopinfo['provinceid'])){
                    $list_city = db("admin_area")->where("pid",$shopinfo['provinceid'])->column("id,name");
                    $list_area = db("admin_area")->where("pid",$shopinfo['cityid'])->column("id,name");
                }else{
                    $list_city ='';
                    $list_area ='';
                }
                // 保存数据
                if ($this->request->isPost()) {
                    $data = $this->request->post();
                        // 验证
                        $result = $this->validate($data, 'AddShop.update');
                    // 验证失败 输出错误信息
                    if(true !== $result){
                        return $this->error($result);
                    }else{
                        $member=$data['mname'][0];
                        $data['memberid']=$member;
                        $res_province=Db::name("admin_area")->where("id=".$data['provinceid'])->find();
                        $res_city=Db::name("admin_area")->where("id=".$data['cityid'])->find();
                        $province=$res_province['name'];
                        $city=$res_city['name'];
                        if(!empty($data['shopcategory'])){
                            $goods=implode(',',$data['shopcategory']);
                            $data['shopcategory']=$goods;
                        }
                        if(!empty($data['townid'])){
                            $res_town=Db::name("admin_area")->where("id=".$data['townid'])->find();
                            $data['town']=$town=$res_town['name'];
                        }
                        if(empty($data['addr'])){
                            if(empty($data['townid'])){
                                $data['addr']=$province.$city;
                            }else{
                                $data['addr']=$province.$city.$town;
                            }
                        }else{
                            if(strpos($data['addr'],'省') || strpos($data['addr'],'市')){
                                $data['addr']=$data['addr'];
                            }else{
                                if(empty($data['townid'])){
                                    $data['addr']=$province.$city.$data['addr'];
                                }else{
                                    $data['addr']=$province.$city.$town.$data['addr'];
                                }
                            }
                        }
                        $data['updatetime']=time();
                    }

                    // 如果没有填写密码，则不更新密码
                    if ($data['password'] == '') {
                        unset($data['password']);
                    }else{
                        $data['password']=crypt($data['password'],'CRYPT_MD5');
                    }
                    $res=Db::name('shop')->update($data);
                    if ($res) {
                        if(!empty($data['shopcategory'])){
                            $type['typeid']=$data['shopcategory'];
                            $typename=explode(',',$type['typeid']);
                            $type_name='';
                            foreach ($typename as $value){
                                $name=Db::name('goods_type')->where('typeid',$value)->field('classname')->find();
                                $type_name.=$name['classname'].',';
                            }
                            $type['typename']=trim($type_name,',');
                            $res_shop=Db::name('type_auditing')->where('shopid',$id)->find();
                            if($res_shop){
                                Db::name('type_auditing')->where('shopid',$id)->update($type);
                            }else{
                                $type['shopid']=$id;
                                Db::name('type_auditing')->insert($type);
                            }

                        }

                        $details = "所属模块('shop'),操作日志('店铺营业执照信息编辑'),店铺编号('$id')";
                        action_log('shop_edit', 'shop', $id, UID, $details);
                        return $this->success('编辑成功');
                    } else {
                        return $this->error('编辑失败');
                    }
                }
                // 使用ZBuilder快速创建表单
                return ZBuilder::make('form')
                    ->setPageTitle('编辑') // 设置页面标题
                    ->setTabNav($list_tab,  $group)
                    ->addFormItems([ // 批量添加表单项
                        ['image', 'shop_logo', '店铺logo', ''],
                        ['select','mname','选择会员','',$arr,$testid,'ajax','',['url'=>'/admin.php/Shop/Shop/memberlist','datakey'=>'id','dataname'=>'name']],
                        ['hidden','id'],
                        ['text', 'name', '店铺名称', ''],
                        ['select', 'shoplevelid', '店铺等级','',$shoplevel],
                        ['select', 'shoptype', '店铺类型', '',$shop_type],
                        ['textarea', 'shopmsg', '店铺描述', ''],
                        ['select', 'shopcategory', '店铺经营类目', '',$shoptype,'','multiple'],
                        ['text', 'contacts', '联系人'],
                        ['text', 'mobile', '手机号'],
                        ['text', 'tel', '固话'],
                        ['text', 'email', '邮箱'],
                        ['text', 'qq', 'qq'],
                        ['password', 'password', '密码'],
                        ['static', 'r', '', ''],
                        ['linkage', 'provinceid', '选择省份','',$list_province,'',url('get_city'),'cityid,townid'],
                        ['linkage', 'cityid', '选择城市','',$list_city,'',url('get_area'),'townid'],
                        ['select', 'townid', '选择区域','',$list_area],
                        ['text', 'addr', '详细地址'],
                        ['radio', 'status', '审核状态', '', $status],
                        ['radio', 'is_enable', '是否启用', '', $is_enable],
                    ])
                    ->layout(['mname'=>3, 'name'=>3,'shoplevelid'=>3,'shoptype'=>3,'shopcategory'=>12,'contacts'=>3,'mobile'=>3,
                        'tel'=>3,'email'=>3,'qq'=>3,'password'=>3,'provinceid'=>2,'cityid'=>2,'townid'=>2,'addr'=>6,'status'=>3,'is_enable'=>3
                    ])
                    ->setFormData($shopinfo) // 设置表单数据
                    ->hideBtn('back')
                    ->addBtn('<button type="button" class="btn btn-default" onclick="back()">返回</button>')
                    ->setExtraJs($js)
                    ->fetch();
                break;
            case 'tab2':
                $shopid=session('id');
                $where['typeid']=1;
                $where['shopid']=$shopid;
                $info=Db::name('business_license')->where($where)->find();
                // 保存数据
                if ($this->request->isPost()) {
                    $data = $this->request->post();
                    // 验证
                    $result = $this->validate($data, 'Business');
                    // 验证失败 输出错误信息
                    if(true !== $result){
                        return $this->error($result);
                    }else{
                      if($info){
                          $res=Db::name('business_license')->where($where)->update($data);
                          if($res){
                              return $this->success('编辑成功');
                          } else {
                              return $this->error('编辑失败');
                          }
                          }else{
                          $data['typeid']=1;
                          $data['shopid']=$shopid;
                          $data['createtime']=time();
                          $data['updatetime']=time();
                          $res=Db::name('business_license')->insert($data);
                          if($res){
                              return $this->success('编辑成功');
                          } else {
                              return $this->error('编辑失败');
                          }
                      }
                      }
                    }
                // 使用ZBuilder快速创建表单
                return ZBuilder::make('form')
                    ->setPageTitle('编辑') // 设置页面标题
                    ->setTabNav($list_tab,  $group)
                    ->addFormItems([ // 批量添加表单项
                        ['text', 'name', '法人代表姓名'],
                        ['image', 'cardimg','法人代表身份证复印件'],
                        ['image', 'shoppersoncodeimg','负责人身份证复印件'],
                        ['static','',''],
                        ['text', 'businesslicenseno', '营业执照号', ''],
                        ['date', 'effectivetime', '营业执照有效期',''],
                        ['image', 'effectiveimg', '营业执照副本图片'],
                        ['static','',''],
                        ['text', 'registeredcapital', '注册资本', ''],
                        ['text', 'organizationcode', '组织机构代码'],
                        ['image', 'organizationcodeimg','组织机构代码证复印件'],
                        ['static','',''],
                        ['text', 'generaltaxpayerproof', '一般纳税人说明'],
                        ['text', 'taxcode', '纳税类型码'],
                        ['text', 'taxno', '税务登记号码'],
                        ['image', 'taximg', '税务登记证复印件'],
                        ['textarea', 'scope', '经营范围', '']
                    ])
                    ->layout(['businesslicenseno'=>3,'effectivetime'=>3,'registeredcapital'=>3,'organizationcode'=>3,'generaltaxpayerproof'=>3,
                        'taxcode'=>3,'taxno'=>3,'effectiveimg'=>3,'taximg'=>3,'organizationcodeimg'=>3,'shoppersoncodeimg'=>3,
                        'name'=>3,'cardimg'=>3,
                    ])
                    ->setFormData($info) // 设置表单数据
                    ->hideBtn('back')
                    ->addBtn('<button type="button" class="btn btn-default" onclick="back()">返回</button>')
                    ->setExtraJs($js)
                    ->fetch();
                break;
            case 'tab3':
                $shop_id = session('id');
                $where['shopid']=$shop_id;
                $info = Db::name('shop_settlement')->where($where)->find();
                // 保存数据
                if ($this->request->isPost()) {
                    $data = $this->request->post();

                    // 验证
                    $result = $this->validate($data, 'ShopSettlement');
                    // 验证失败 输出错误信息
                    if(true !== $result){
                        return $this->error($result);
                    }else {
                        if($info){
                            $data['updatetime']=time();
                            $res_bank = Db::name('shop_settlement')->where($where)->update($data);
                            if ($res_bank) {
                                return $this->success('编辑成功');
                            } else {
                                return $this->error('编辑失败');
                            }
                        }else{
                            $data['shopid']=$shop_id;
                            $data['createtime']=time();
                            $data['updatetime']=time();
                            $ress=Db::name('shop_settlement')->insert($data);
                            if ($ress) {
                                return $this->success('新增成功');
                            } else {
                                return $this->error('新增失败');
                            }
                        }

                    }
                }
                return ZBuilder::make('form')
                    ->setTabNav($list_tab,  $group)
                    ->setPageTitle('编辑银行信息') // 设置页面标题
                    ->addFormItems([ // 批量添加表单项
                        ['text', 'account_name', '银行开户名', ''],
                        ['text', 'bank_no', '公司银行账户',''],
                        ['text', 'bank_name', '开户银行支行名称', ''],
                        ['text', 'subbranch_id', '支行联行号', ''],
                        ['text', 'band_addr', '开户银行所在地', ''],
                    ])
                    ->layout(['account_name'=>4,'bank_no'=>4,'bank_name'=>4,'subbranch_id'=>4,'band_addr'=>4 ])
                    ->setFormData($info) // 设置表单数据
                    ->hideBtn('back')
                    ->addBtn('<button type="button" class="btn btn-default" onclick="back()">返回</button>')
                    ->setExtraJs($js)
                    ->fetch();
                break;
            case 'tab4':
                $shop_id = session('id');
                $where['shopid']=$shop_id;
                $where['typeid']=1;
                $info = Db::name('member_balance')->where($where)->find();
                $invoiceType=Db::name('invoice_type')->where('status=1')->column('invoice_id,invoice_type');
                $list_province = db("admin_area")->where("pid=0")->column("id,name");
                if(!empty($info['provinceid'])){
                    $list_city = db("admin_area")->where("pid",$info['provinceid'])->column("id,name");
                    $list_area = db("admin_area")->where("pid",$info['cityid'])->column("id,name");
                }else{
                    $list_city ='';
                    $list_area ='';
                }
                if(!empty($info['c_provinceid'])){
                    $c_cityid = db("admin_area")->where("pid",$info['c_provinceid'])->column("id,name");
                    $c_areaid = db("admin_area")->where("pid",$info['c_cityid'])->column("id,name");
                }else{
                    $c_cityid ='';
                    $c_areaid ='';
                }
                // 保存数据
                if ($this->request->isPost()) {
                    $data = $this->request->post();

                    // 验证
                    $result = $this->validate($data, 'Bank');
                    // 验证失败 输出错误信息
                    if(true !== $result){
                        return $this->error($result);
                    }else {
                        $c_province=Db::name("admin_area")->where("id=".$data['c_provinceid'])->find();
                        $c_city=Db::name("admin_area")->where("id=".$data['c_cityid'])->find();
                        if(!empty($data['c_townid'])){
                            $c_town=Db::name("admin_area")->where("id=".$data['c_townid'])->find();
                        }
                        if(empty($data['bandaddr'])){
                            if(empty($c_town['name'])){
                                $data['bandaddr']=$c_province['name'].$c_city['name'];
                            }else{
                                $data['bandaddr']=$c_province['name'].$c_city['name'].$c_town['name'];
                            }
                        }else{
                            if(strpos($data['bandaddr'],'省') || strpos($data['bandaddr'],'市')){
                                $data['bandaddr']=$data['bandaddr'];
                            }else{
                                if(empty($c_town['name'])){
                                    $data['bandaddr']=$c_province['name'].$c_city['name'].$data['bandaddr'];
                                }else{
                                    $data['bandaddr']=$c_province['name'].$c_city['name'].$c_town['name'].$data['bandaddr'];
                                }
                            }
                        }
                        $res_province=Db::name("admin_area")->where("id=".$data['provinceid'])->find();
                        $res_city=Db::name("admin_area")->where("id=".$data['cityid'])->find();
                        if(!empty($data['townid'])){
                            $res_town=Db::name("admin_area")->where("id=".$data['townid'])->find();
                        }
                        if(empty($data['signup_address'])){
                            if(empty($res_town['name'])){
                                $data['signup_address']=$res_province['name'].$res_city['name'];
                            }else{
                                $data['signup_address']=$res_province['name'].$res_city['name'].$res_town['name'];
                            }
                        }else{
                            if(strpos($data['signup_address'],'省') || strpos($data['signup_address'],'市')){
                                $data['signup_address']=$data['signup_address'];
                            }else{
                                if(empty($res_town['name'])){
                                    $data['signup_address']=$res_province['name'].$res_city['name'].$data['signup_address'];
                                }else{
                                    $data['signup_address']=$res_province['name'].$res_city['name'].$res_town['name'].$data['signup_address'];
                                }
                            }
                        }
                        if($info){
                            $data['updatetime']=time();
                            $res_bank = Db::name('member_balance')->where($where)->update($data);
                            if ($res_bank) {
                                return $this->success('编辑成功',cookie('__forward__'));
                            } else {
                                return $this->error('编辑失败');
                            }
                        }else{
                            $data['shopid']=$shop_id;
                            $data['typeid']=1;
                            $data['createtime']=time();
                            $data['updatetime']=time();
                            $ress=Db::name('member_balance')->insert($data);
                            if ($ress) {
                                return $this->success('新增成功');
                            } else {
                                return $this->error('新增失败');
                            }
                        }

                    }
                }
                return ZBuilder::make('form')
                    ->setTabNav($list_tab,  $group)
                    ->setPageTitle('编辑开票信息') // 设置页面标题
                    ->addFormItems([ // 批量添加表单项
                        ['select', 'invoice_type', '发票类型','',$invoiceType],
                        ['text', 'company', '单位名称', ''],
                        ['text', 'taxpayer_no', '纳税人识别号', ''],
                        ['text', 'tel', '电话', ''],
                        ['text', 'accountname', '银行开户名', ''],
                        ['text', 'bankno', '公司银行账户',''],
                        ['text', 'bankname', '开户银行支行名称', ''],
                        ['text', 'bankid', '支行联行号', ''],
                        ['linkage', 'c_provinceid', '选择省份','',$list_province,'',url('c_city'),'c_cityid,c_townid'],
                        ['linkage', 'c_cityid', '选择城市','',$c_cityid,'',url('c_area'),'c_townid'],
                        ['select', 'c_townid', '选择区域','',$c_areaid],
                        ['text', 'bandaddr', '开户银行所在地', ''],
                        ['linkage', 'provinceid', '选择省份','',$list_province,'',url('get_city'),'cityid,townid'],
                        ['linkage', 'cityid', '选择城市','',$list_city,'',url('get_area'),'townid'],
                        ['select', 'townid', '选择区域','',$list_area],
                        ['text', 'signup_address', '注册地址', ''],
                    ])
                    ->layout(['accountname'=>3,'bankno'=>3,'bankname'=>3,'bankid'=>3,'bandaddr'=>3,'invoice_type'=>3,
                        'company'=>3,'taxpayer_no'=>3,'tel'=>3,'provinceid'=>3,'cityid'=>3,'townid'=>3,'signup_address'=>3,'c_provinceid'=>3,'c_cityid'=>3,'c_townid'=>3])
                    ->setFormData($info) // 设置表单数据
                    ->hideBtn('back')
                    ->addBtn('<button type="button" class="btn btn-default" onclick="back()">返回</button>')
                    ->setExtraJs($js)
                    ->fetch();
                break;

        }
    }
    //查看店铺信息
    public function look($id='',$group = 'tab1'){
        $list_tab = [
            'tab1' => ['title' => '基础信息', 'url' => url('look', ['group' => 'tab1'])],
            'tab2' => ['title' => '证照信息', 'url' => url('look', ['group' => 'tab2'])],
//            'tab3' => ['title' => '银行信息', 'url' => url('look', ['group' => 'tab3'])],
            'tab4' => ['title' => '开票信息', 'url' => url('look', ['group' => 'tab4'])],
        ];
        $url=cookie('__forward__');
        $js = <<<EOF
            <script type="text/javascript">
              function back(){
              window.location.href="$url";
              }
            </script>
EOF;
        session('id',$id);
        switch ($group) {
            case 'tab1':
                $shop_id=session('id');
                $info=Db::name('shop')->where('id',$shop_id)->find();
                $member_name=Db::name('member')->where('id',$info['memberid'])->find();
                $info['memberid']=$member_name['name'];
                $address=getArea($info['provinceid'],$info['cityid'],$info['townid']);
                $info['address']=$address;
                $status=ShopStatusModel::getstatusAttr($info['status']);
                $info['status']=$status;
                $is_enable=ShopStatusModel::getShopIsEnable($info['is_enable']);
                $info['is_enable']=$is_enable;
                $shoplevel=Db::name('shop_level')->where('id',$info['shoplevelid'])->field('shopname')->find();
                $info['shoplevelid']=$shoplevel['shopname'];
                $typename=Db::name('shop_type')->where('id',$info['shoptype'])->field('shoptype')->find();
                $info['shoptype']=$typename['shoptype'];
                if(!empty($info['shopcategory'])){
                    $type=explode(',',$info['shopcategory']);
                    $shopcategory='';
                    foreach ($type as $value){
                        $shoptype=Db::name("goods_type")->where('typeid',$value)->field("classname")->find();
                        $shopinfo=$shoptype['classname'];
                        $shopcategory.=$shopinfo.',';
                    }
                    $info['shopcategory']=trim($shopcategory,',');
                }
                $info['createtime']=date('Y-m-d H:i:s',$info['createtime']);
                $info['updatetime']=date('Y-m-d H:i:s',$info['updatetime']);
                // 使用ZBuilder快速创建表单
                return ZBuilder::make('form')
                    ->setPageTitle('查看店铺信息') // 设置页面标题
                    ->setTabNav($list_tab,  $group)
                    ->addFormItems([ // 批量添加表单项
                        ['image','shop_logo','店铺logo'],
                        ['static','memberid','会员',''],
                        ['hidden','id'],
                        ['static', 'name', '店铺名称', ''],
                        ['static', 'shoplevelid', '店铺等级',''],
                        ['static', 'shoptype', '店铺类型', ''],
                        ['static', 'shopmsg', '店铺描述', ''],
                        ['static', 'shopcategory', '店铺经营类目', ''],
                        ['static', 'r', '', ''],
                        ['static', 'contacts', '联系人'],
                        ['static', 'mobile', '手机号'],
                        ['static', 'tel', '固话'],
                        ['static', 'email', '邮箱'],
                        ['static', 'qq', 'qq'],
                        ['static', 'r', '', ''],
                        ['static', 'address', '地区', ''],
                        ['static', 'addr', '详细地址'],
                        ['static', 'createtime', '添加时间',''],
                        ['static', 'updatetime', '更新时间',''],
                        ['static', 'r', '', ''],
                        ['static', 'status', '审核状态', ''],
                        ['static', 'is_enable', '是否启用', ''],


                    ])
                    ->layout(['memberid'=>3, 'name'=>3,'shoplevelid'=>3,'shoptype'=>3,'shopcategory'=>12,'contacts'=>3,'mobile'=>3,'tel'=>3,'email'=>3,'qq'=>3,'password'=>3,'address'=>5,'addr'=>7,'createtime'=>3,'updatetime'=>3,
                        'status'=>3,'is_enable'=>3
                    ])
                    ->setFormData($info) // 设置表单数据
                    ->hideBtn('submit,back')
                    ->addBtn('<button type="button" class="btn btn-default" onclick="back()">返回</button>')
                    ->setExtraJs($js)
                    ->fetch();
                break;
            case 'tab2':
                $shop_id=session('id');
                $where['shopid']=$shop_id;
                $where['typeid']=1;
                $info=Db::name('business_license')->where($where)->find();
                if(!empty($info['createtime'])){
                    $info['createtime']=date('Y-m-d H:i:s',$info['createtime']);
                }
                if(!empty($info['updatetime'])){
                    $info['updatetime']=date('Y-m-d H:i:s',$info['updatetime']);
                }
                // 使用ZBuilder快速创建表单
                return ZBuilder::make('form')
                    ->setPageTitle('查看证照信息') // 设置页面标题
                    ->setTabNav($list_tab,  $group)
                    ->addFormItems([ // 批量添加表单项
                        ['static', 'name', '法人代表姓名'],
                        ['image', 'cardimg','法人代表身份证复印件'],
                        ['image', 'shoppersoncodeimg','负责人身份证复印件'],
                        ['static','',''],
                        ['static', 'businesslicenseno', '营业执照号', ''],
                        ['static', 'effectivetime', '营业执照有效期',''],
                        ['image', 'effectiveimg', '营业执照副本图片'],
                        ['static','',''],
                        ['static', 'registeredcapital', '注册资本', ''],
                        ['static', 'organizationcode', '组织机构代码'],
                        ['image', 'organizationcodeimg','组织机构代码证复印件'],
                        ['static','',''],
                        ['static', 'generaltaxpayerproof', '一般纳税人说明'],
                        ['static', 'taxcode', '纳税类型码'],
                        ['static', 'taxno', '税务登记号码'],
                        ['image', 'taximg', '税务登记证复印件'],
                        ['static', 'scope', '经营范围', ''],
                        ['static', 'createtime', '添加时间', ''],
                        ['static', 'updatetime', '修改时间',''],

                    ])
                    ->layout(['businesslicenseno'=>3,'effectivetime'=>3,'registeredcapital'=>3,'organizationcode'=>3,'generaltaxpayerproof'=>3,
                        'name'=>3,'taxcode'=>3,'taxno'=>3,'effectiveimg'=>3,'taximg'=>3,'organizationcodeimg'=>3,'shoppersoncodeimg'=>3,
                        'createtime'=>3,'updatetime'=>3,'cardimg'=>3,

                    ])
                    ->setFormData($info) // 设置表单数据
                    ->hideBtn('submit,back')
                    ->addBtn('<button type="button" class="btn btn-default" onclick="back()">返回</button>')
                    ->setExtraJs($js)
                    ->fetch();
                break;
            case 'tab3':
                $shop_id = session('id');
                $where['shopid']=$shop_id;
                $info = Db::name('shop_settlement')->where($where)->find();
                return ZBuilder::make('form')
                    ->setTabNav($list_tab,  $group)
                    ->setPageTitle('编辑银行信息') // 设置页面标题
                    ->addFormItems([ // 批量添加表单项
                        ['text', 'account_name', '银行开户名', ''],
                        ['text', 'bank_no', '公司银行账户',''],
                        ['text', 'bank_name', '开户银行支行名称', ''],
                        ['text', 'subbranch_id', '支行联行号', ''],
                        ['text', 'band_addr', '开户银行所在地', ''],
                    ])
                    ->layout(['account_name'=>4,'bank_no'=>4,'bank_name'=>4,'subbranch_id'=>4,'band_addr'=>4 ])
                    ->setFormData($info) // 设置表单数据
                    ->hideBtn('submit,back')
                    ->addBtn('<button type="button" class="btn btn-default" onclick="back()">返回</button>')
                    ->setExtraJs($js)
                    ->fetch();
                break;
            case 'tab4':
                $shop_id = session('id');
                $where['shopid']=$shop_id;
                $where['typeid']=1;
                $info = Db::name('member_balance')->where($where)->find();
                $map['status']=1;
                $map['invoice_id']=$info['invoice_type'];
                $invoiceType=Db::name('invoice_type')->where($map)->field('invoice_type')->find();
                $info['invoice_type']=$invoiceType['invoice_type'];
                // 使用ZBuilder快速创建表单
                return ZBuilder::make('form')
                    ->setPageTitle('查看开票信息') // 设置页面标题
                    ->setTabNav($list_tab,  $group)
                    ->addFormItems([ // 批量添加表单项
                        ['static', 'invoice_type', '发票类型',],
                        ['static', 'company', '单位名称', ''],
                        ['static', 'taxpayer_no', '纳税人识别号', ''],
                        ['static', 'tel', '电话', ''],
                        ['static', 'accountname', '银行开户名', ''],
                        ['static', 'bankno', '公司银行账户',''],
                        ['static', 'bankname', '开户银行支行名称', ''],
                        ['static', 'bankid', '支行联行号', ''],
                        ['text', 'bandaddr', '开户银行所在地', ''],
                        ['text', 'signup_address', '注册地址', ''],
                        ['static', '', '', ''],
                        ['static', 'createtime', '添加日期'],
                        ['static', 'updatetime', '更新日期'],
                    ])
                    ->layout(['accountname'=>3,'bankno'=>3,'bankname'=>3,'bankid'=>3,'bandaddr'=>4,'invoice_type'=>3,
                        'company'=>3,'taxpayer_no'=>3,'tel'=>3,'signup_address'=>4,'createtime'=>3,'updatetime'=>3])
                    ->setFormData($info) // 设置表单数据
                    ->hideBtn('submit,back')
                    ->addBtn('<button type="button" class="btn btn-default" onclick="back()">返回</button>')
                    ->setExtraJs($js)
                    ->fetch();
                break;
        }
    }
    public function get_city($provinceid = '') {
        $result =Db::name("admin_area")->where("pid=$provinceid")->field("id,name")->select();
        $list=[];
        foreach ($result as $key => $value) {
            # code...
            $list[$key]['key']=$value['id'];
            $list[$key]['value']=$value['name'];
        }

        $arr['code'] = '1'; //判断状态
        $arr['msg'] = '请求成功'; //回传信息
        $arr['list'] = $list; //数据
        return json($arr);
    }

    public function get_area($cityid = '') {
        $result =Db::name("admin_area")->where("pid=$cityid")->field("id,name")->select();
        $list=[];
        foreach ($result as $key => $value) {
            # code...
            $list[$key]['key']=$value['id'];
            $list[$key]['value']=$value['name'];
        }

        $arr['code'] = '1'; //判断状态
        $arr['msg'] = '请求成功'; //回传信息
        $arr['list'] = $list; //数据
        return json($arr);
    }
    public function c_city($c_provinceid = '') {
        $result =Db::name("admin_area")->where("pid=$c_provinceid")->field("id,name")->select();
        $list=[];
        foreach ($result as $key => $value) {
            # code...
            $list[$key]['key']=$value['id'];
            $list[$key]['value']=$value['name'];
        }

        $arr['code'] = '1'; //判断状态
        $arr['msg'] = '请求成功'; //回传信息
        $arr['list'] = $list; //数据
        return json($arr);
    }

    public function c_area($c_cityid = '') {
        $result =Db::name("admin_area")->where("pid=$c_cityid")->field("id,name")->select();
        $list=[];
        foreach ($result as $key => $value) {
            # code...
            $list[$key]['key']=$value['id'];
            $list[$key]['value']=$value['name'];
        }

        $arr['code'] = '1'; //判断状态
        $arr['msg'] = '请求成功'; //回传信息
        $arr['list'] = $list; //数据
        return json($arr);
    }

    //批量审核店铺
    public function enable($record = [])
    {
        $ids=input('');
        $ids=implode(',',$ids['ids']);
        $data=array('status'=>1);
        $details = "所属模块('shop'),操作日志('批量审核启用店铺'),店铺id('$ids')";
        action_log('shop_enable', 'shop', $ids, UID, $details);
        $this->auditing($data);
    }
    //批量审核禁用店铺
    public function disable($record = [])
    {
        $ids=input('');
        $ids=implode(',',$ids['ids']);
        $data=array('is_enable'=>0);
        $details = "所属模块('shop'),操作日志('批量审核禁用店铺'),店铺id('$ids')";
        action_log('shop_disable', 'shop', $ids, UID, $details);
        $this->auditing($data);
    }
    //批量审核启用店铺
    public function isenable()
    {
        $data=array('is_enable'=>1);
        $this->auditing($data);
    }
    public function auditing($data){
        $ids= $this->request->isPost() ? input('post.ids/a') : input('param.ids');
        foreach ($ids as $values){
            $res=Db::name("shop")->where('id',$values)->update($data);
        }
        if ($res) {
            return $this->success('操作成功',url('shop/Shop/index'));
        } else {
            return $this->error('操作失败');
        }
    }
    //选择会员列表
    public function memberlist(){
        $search=input('q');
        $where['name']=['like',"%$search%"];
        $where['status']=1;
        $member=Db::name('member')->field('id,name')->where($where)->select();
        $memberlist=[];
        $a= 0;
        foreach($member as $value){
            $b = $a++;
            $key=$value['id'];
            $memberlist[$b]['id']=$key;
            $memberlist[$b]['name']=$value['name'];
        }
        return json(['items'=>$memberlist,'total_count'=>sizeof($memberlist)]);
    }

}